package com.ycz;

import lombok.SneakyThrows;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 编程式事务
 *
 * @author ycz
 * @date 2021/6/25
 */
public class ProcessTransactionTest {

    static final String url="jdbc:mysql://localhost:3306/mine?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    static final String user="root";
    static final String password="123456";

    public static void main(String[] args) {
        //
        DataSource dataSource = new DriverManagerDataSource(url, user, password);
        // 创建事务模板
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        // 开启事务管理器
        transactionTemplate.setTransactionManager(new DataSourceTransactionManager(dataSource));

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @SneakyThrows
            @Override
            public Object doInTransaction(TransactionStatus status) {
                Connection connection = dataSource.getConnection();
                Object savePoint = null;
                // 插入
                PreparedStatement statement = connection.prepareStatement("insert into t_user values (1,1,1)");
                statement.execute();
                // 设置保存点
                savePoint = status.createSavepoint();
                // 插入
                PreparedStatement statement2 = connection.prepareStatement("insert into t_user values (2,2,2)");
                statement2.execute();
//                connection.prepareStatement()

                return null;
            }
        });

    }

}
